import { createRouter, createWebHistory } from 'vue-router'
import HomePage from '@v/HomePage/index.vue'
import { isLogin } from '@/utils'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/home'
    },
    {
      path: '/home',
      name: 'home',
      component: HomePage
    },
    {
      path: '/cate',
      name: 'cate',
      component: () => import('@v/CatePage/index.vue')
    },
    {
      path: '/cart',
      meta: {
        needAuth: true
      },
      name: 'cart',
      component: () => import('@v/CartPage/index.vue')
    },
    {
      path: '/user',
      meta: {
        needAuth: true
      },
      name: 'user',
      component: () => import('@v/UserPage/index.vue')
    },
    {
      path: '/detail',
      name: 'detail',
      component: () => import('@v/ItemDetail/index.vue')
    },
    {
      path: '/itemLists',
      name: 'itemLists',
      component: () => import('@v/ItemLists/index.vue')
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@v/UserLogin/index.vue')
    },
    {
      path: '/reg',
      name: 'reg',
      component: () => import('@v/UserReg/index.vue')
    }
  ]
})

router.beforeEach((to, from) => {
  if (to.meta.needAuth) {
    // 需要登录才能访问
    if (!isLogin()) {
      return {
        path: '/login',
        query: {
          from: to.path
        }
      }
    }
  }
})

export default router
